// 定位信息

import {
  getGeoLocation,
  getIpLocation,
} from '@/api'


const state = {
  location: {
    code: 0, // 未授权，1-成功，-1授权失败
  },

  geoLocation: {},
}

const mutations = {
  // 更新定位
  UPDATE_LOCATION: (state, data) => {
    state.location = data
  },

  // 更新地理位置
  UPDATE_GEO_LOCATION: (state, data) => {
    state.location = data
  },
}

const actions = {
  // 获取用户定位
  getLocation({ commit, dispatch }, needGeoLocation) {
    // #ifdef H5
    // h5 不充值无法调用地图获取位置信息
    return new Promise(resolve => {
      if ("geolocation" in navigator) {
        // geolocation is available
        navigator.geolocation.getCurrentPosition(async position => {
          const data = {
            code: 1,
            latitude:  position.coords.latitude,
            longitude:  position.coords.longitude,
          }
          commit('UPDATE_LOCATION', data)
          // 是否需要用经纬度获取地理信息
          if (needGeoLocation) {
            const geoLocation = await dispatch('loadGeoLocation', {
              lat: data.latitude,
              lng: data.longitude
            })
            resolve({location: data, geoLocation})
          } else {
            resolve(data)
          }
        }, (error) => {
          console.log(error)
          // 获取位置失败，采用ip定位
          dispatch('loadIpLocation').then(geoLocation => {
            if (geoLocation.address) {
              resolve({location: {code: 1}, geoLocation})
            } else {
              resolve({ location: {code: -1} })
            }
          })
        }, {
          enableHighAccuracy: true,
          timeout: 3000,
          maximumAge: 0,
        });
      } else {
        console.log('获取失败')
        // 获取位置失败，采用ip定位
        dispatch('loadIpLocation').then(geoLocation => {
          if (geoLocation.address) {
            resolve({ location: {code: 1}, geoLocation })
          } else {
            resolve({ location: {code: -1} })
          }
        })
      }
    })
    // #endif

    // #ifndef H5
    return new Promise((resolve) => {
      uni.getLocation({
        type: 'gcj02',
        success: async res => {
          const { longitude, latitude } = res
          if (longitude && latitude) {
            const data = { code: 1, longitude, latitude }
            commit('UPDATE_LOCATION', data)
            // 是否需要用经纬度获取地理信息
            if (needGeoLocation) {
              const geoLocation = await dispatch('loadGeoLocation', {
                lat: latitude,
                lng: longitude
              })
              resolve({location: data, geoLocation})
            } else {
              resolve(data)
            }
          } else {
            const data = { code: -1 }
            commit('UPDATE_LOCATION', data)
            resolve(data)
          }
        },
        fail: res => {
          const data = { code: -1 }
          commit('UPDATE_LOCATION', data)
          resolve(data)
        }
      })
    })
    // #endif
    
  },

  // 根据经纬度
  loadGeoLocation({ commit }, params) {
    return new Promise(resolve => {
      getGeoLocation(params).then(({ data, code }) => {
        if (code === 200) {
          commit('UPDATE_GEO_LOCATION', data)
          resolve(data)
        } else {
          resolve({})
        }
      })
    })
  },

  // 根据Ip定位
  loadIpLocation({ commit }) {
    return new Promise(resolve => {
      getIpLocation().then(({ data, code }) => {
        if (code === 200) {
          commit('UPDATE_GEO_LOCATION', data)
          resolve(data)
        } else {
          resolve({})
        }
      })
    }) 
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}